package implementation;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;

import started.ReadPropertiesHost;
import utilities.Amostragem;
import entility.Job;
import entility.JobImpl;
import entility.Machine;
import entility.Notification;
import entility.Range;

public class Sample extends Thread{

	private Job job;
	private File[] file;

	

	public Sample(Job job, File[] file)
	{
		this.job = job;
		this.file = file;
	}





	public List<Range> executeSample(File file)
	{

		int sampleSize = 5000;
		int numberOfBukets = 50;
		
		//String path = ReadPropertiesHost.GetInstance().getPath();
		
		Amostragem a = new Amostragem(file, sampleSize);
		Queue<Range> q = a.getBuckets(numberOfBukets);
		
		
		int bestNumber = numberOfBukets/10;
		List<Range> bestRanges = new LinkedList<Range>(); 
		int i=0;
		int before = 0;
		int current = 0;
		
		while( q.size()>0 &&(i< bestNumber || before == current ))
		{
			before = current;
			Range r = q.poll();
			current = r.getSize();
			
			bestRanges.add(r);
			i++;
		}

		
		return bestRanges;
		//sendToServerTheSamples(bestRanges);
		
		
	}

	
	public void sendToServerTheSamples(List<Range> bestRanges)
	{
		Job sampleFinish = new JobImpl(Notification.HOST);
		sampleFinish.setMethod("amostragemConcluida");
		//sampleFinish.setData(HostImpl.meMyselfandI);

		Map<Machine, List<Range> > listaIntervalos = new HashMap<Machine, List<Range>>();
		listaIntervalos.put(HostImpl.meMyselfandI, bestRanges);
		sampleFinish.setData(listaIntervalos);
		
		
		try{

			HostImpl.primaryServer.getMessage(sampleFinish);

		}catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	
	
	public void amostra()
	{
		
		Queue<Range > ranges = new PriorityQueue<Range>();
		/*for(File f:file)
		{
			ranges.addAll(this.executeSample(f));
		}*/
		
		ranges.addAll(this.executeSample(file[0]));
		
		
		List< Range> rangesToSend = new ArrayList<Range>(ranges);
		
		//sendToServerTheSamples(rangesToSend.subList(0, 4));
		List<Range> subListToSend = new ArrayList<Range>();
		for(int i = 0; i < 4;i++){
			subListToSend.add(rangesToSend.get(i));
		}
		
		sendToServerTheSamples(subListToSend);
		
		
	}
	
	

	public void run()
	{
		this.amostra();
	}
}
